package com.greenline.push.dal.base;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

/**
 * @Type PageDAO
 * @Desc DAO基类
 * @author weirui.shenwr
 * @date 2012-3-23
 * @Version V1.0
 */
public class BaseDAO extends SqlMapClientDaoSupport {

    @SuppressWarnings("unchecked")
    protected <T> PageQuery<T> listByQuery(String statementName, PageQuery<T> query) {
        // 获取总记录数
        query.setTotalRecord(countByQuery(statementName + "_count", query));
        // 如果有记录
        if (query.getTotalRecord() > 0) {
            List<T> result = (List<T>) getSqlMapClientTemplate().queryForList(statementName, query);
            if (result == null) {
                result = new ArrayList<T>();
            }
            query.setDataList(result);
        }
        return query;
    };

    /**
     * 
     * @param statementName
     * @param query
     * @param map 自定义参数
     * @return
     */
    @SuppressWarnings("unchecked")
    protected <T> PageQuery<T> listByQuery(String statementName, PageQuery<T> query,
            @SuppressWarnings("rawtypes") Map map) {
        // 获取总记录数
        Integer total = countByQuery(statementName + "_count", map);
        query.setTotalRecord(total);
        // 如果有记录
        if (query.getTotalRecord() > 0 && query.getPageIndex() <= query.getTotalPage()) {
            int pageSize = query.getPageSize();
            int currentPage = query.getPageIndex();
            if (currentPage < 1) {
                currentPage = 1;
            }
            map.put("offset", pageSize * (currentPage - 1));
            map.put("pageSize", (currentPage) * pageSize);
            List<T> result = (List<T>) getSqlMapClientTemplate().queryForList(statementName, map);
            if (result == null) {
                result = new ArrayList<T>();
            }
            query.setDataList(result);
        }
        return query;
    };

    /**
     * 获取总数
     * 
     * @param statementName
     * @param query
     * @return
     */
    public <T> Integer countByQuery(String statementName, PageQuery<T> query) {
        return (Integer) getSqlMapClientTemplate().queryForObject(statementName, query);
    }

    /**
     * 获取总数
     * 
     * @param statementName
     * @param query
     * @return
     */
    public <T> Integer countByQuery(String statementName, @SuppressWarnings("rawtypes") Map map) {
        return (Integer) getSqlMapClientTemplate().queryForObject(statementName, map);
    }
}
